<?php

require_once 'Zend/Db/Table/Abstract.php';

abstract class Base_Db_Table extends Zend_Db_Table_Abstract
{
    protected $_modelName = NULL;
	protected $_fields    = array();
	
	public function check($key, $val)
	{
	}
	
	public function readBy($key, $val)
	{
        return $this->_db->fetchRow(
                    $this->select()
                         ->where('`'.$key.'` = ?', $val)
                );
	}
	
	public function read($id)
	{
        if (empty($id)) {
            return false;
        }
		$result = $this->find($id);
		if (0 != count($result)) {
			return $result->current();
		}
	}

	public function save(Base_Model $model)
	{
		$data = array();
		foreach ($model->toArray() as $field => $value) {
			if (in_array($field, $this->_fields) && $value != '') {
				$data[$field] = $value;
			}
		}

        try {
            if (null != $model->{$this->getPrimary()}) {
                $result = $this->update($data, array($this->getPrimary() .' = ?' => $model->{$this->getPrimary()}));
                
                if ($result != null) {
                    return;
                }
            }
            
            $this->insert($data);
        } catch (Exception $e) {
            throw new Base_Db_Exception(
                $e->getPrevious()->errorInfo[2],
                $e->getPrevious()->errorInfo[1],
                $e
            );
        }
	}
	
	public function view(array $where= NULL, $order= NULL, $count= NULL, $offset= NULL)
	{
		$results = $this->fetchAll($where, $order, $count, $offset);
		$entries = array();
		foreach ($results->toArray() as $data) {
			$entries[] = new $this->_modelName($data);
		}
		return $entries;
	}
	
	public function getPrimary()
	{
        $this->_setupPrimaryKey();
        return $this->_primary[1];
    }
}